package com.szt.sy.service.blog.article;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.szt.sy.entity.blog.Article;
import com.szt.sy.mapper.blog.ArticleMapper;
import com.szt.sy.service.blog.articletag.ArticleTagService;

/***
 * 文章服务
 * 
 * @author wwy
 *
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class ArticleService extends ServiceImpl<ArticleMapper, Article> {
	
	@Autowired
	private ArticleTagService articleTagService;
	
	public void addRecord(Article article) {
		insert(article);
		if (StringUtils.isNotBlank(article.getTags())) {
			String[] tagArray = article.getTags().split(",");
			for (String tag : tagArray) {
				articleTagService.increase(tag);
			}
		}
	}
	
	public void editRecord(Article article) {
		Article oldArticle = selectById(article.getId());
		String oldTags = oldArticle.getTags();
		if (StringUtils.isNotBlank(oldTags)) {
			String[] tagArray = oldTags.split(",");
			for (String tag : tagArray) {
				articleTagService.decrease(tag);
			}
		}
		if (StringUtils.isNotBlank(article.getTags())) {
			String[] tagArray = article.getTags().split(",");
			for (String tag : tagArray) {
				articleTagService.increase(tag);
			}
		}
		updateById(article);
	}
	
	public void deleteRecord(Long id) {
		Article oldArticle = selectById(id);
		String oldTags = oldArticle.getTags();
		if (StringUtils.isNotBlank(oldTags)) {
			String[] tagArray = oldTags.split(",");
			for (String tag : tagArray) {
				articleTagService.decrease(tag);
			}
		}
		deleteById(id);
	}
	
	public void deleteRecords(List<Long> ids) {
		if (ids != null) {
			for (Long id : ids) {
				deleteRecord(id);
			}
		}
	}
	
	/**
	 * 列表
	 *
	 * @param page
	 * @
	 */
	public Page<Article> list(Page<Article> page, Map<String, Object> map) {
		page.setRecords(baseMapper.datalistPage(page, map));
		return page;
	}
	
	/**
	 * 列表(全部)
	 *
	 * @param pd
	 * @
	 */
	public List<Article> listAll(Map<String, Object> map) {
		return baseMapper.listAll(map);
	}
	
	public void increaseViews(Long id) {
		baseMapper.increaseViews(id);
	}
	
	public void increaseComments(Long id) {
		baseMapper.increaseComments(id);
	}
	
}
